package org.blueoxygen.kukuruyuk.actions.location;
import java.lang.reflect.InvocationTargetException;
import java.sql.Timestamp;
import org.apache.commons.beanutils.PropertyUtils;
import org.blueoxygen.cimande.LogInformation;
import org.blueoxygen.kukuruyuk.entity.Location;
public class SaveLocation extends LocationForm {
	
	
	private String population = "";
	public String execute(){
		if(getLocation().getName() == null ||
				"".equalsIgnoreCase(getLocation().getName())){
				addActionError("Masukkan nama lokasi !");
		}
		if (getLocation().getAddress() == null ||
				"".equalsIgnoreCase(getLocation().getAddress())){
				addActionError("Masukkan alamat lokasi !");
		}
		
		if(getPopulation() == null || "".equalsIgnoreCase(getPopulation())){
			addActionError("Masukkan jumlah populasi !");
		}
		
		if(hasErrors()){
			return INPUT;
		}
		LogInformation log;
		if(getLocation().getId() == null ||
				"".equalsIgnoreCase(getLocation().getId())){
			log = new LogInformation();
			log.setCreateBy(sessionCredentials.getCurrentUser().getId());
			log.setCreateDate(new Timestamp(System.currentTimeMillis()));
			getLocation().setId(null);
		} else {
			Location temp = getLocation();
			setLocation((Location) manager.getById(Location.class, getLocation().getId()));
			log = getLocation().getLogInformation();
			try {
				PropertyUtils.copyProperties(getLocation(), temp);
			} catch (IllegalAccessException e) {
				e.printStackTrace();
			} catch (InvocationTargetException e) {
				e.printStackTrace();
			} catch (NoSuchMethodException e) {
				e.printStackTrace();
			}
		}
		int intPopulation = Integer.parseInt(getPopulation());
		log.setLastUpdateBy(sessionCredentials.getCurrentUser().getId());
		log.setLastUpdateDate(new Timestamp(System.currentTimeMillis()));
		log.setActiveFlag(1);
		getLocation().setPopulation(intPopulation);
		getLocation().setLogInformation(log);
		manager.save(getLocation());
		return SUCCESS;
	}
	public String getPopulation() {
		return population;
	}
	public void setPopulation(String population) {
		this.population = population;
	}
	
}